﻿using Common.Caching;
using MediatR;
using Microsoft.Extensions.Logging;

namespace Common.Behaviours;

/// <summary>
/// 添加缓存
/// </summary>
/// <typeparam name="TRequest"></typeparam>
/// <typeparam name="TResponse"></typeparam>
public class CacheBehaviour<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
    where TRequest : ICacheableRequest<TResponse>
{
    private readonly ICacheService _cache;
    private readonly ILogger<CacheBehaviour<TRequest, TResponse>> _logger;

    public CacheBehaviour(
        ICacheService cache,
        ILogger<CacheBehaviour<TRequest, TResponse>> logger
        )
    {
        _cache = cache;
        _logger = logger;
    }
    public async Task<TResponse> Handle(TRequest request, RequestHandlerDelegate<TResponse> next, CancellationToken cancellationToken)
    {
        _logger.LogDebug("{Name} 正在缓存 {@Request}", nameof(request), request);
        var response = await _cache.GetOrAddAsync(
            request.CacheKey,
            async () =>
            await next(),
            request.Options!).ConfigureAwait(false);

        return response;
    }
}
